package org.i1510.common.utils;

import java.io.UnsupportedEncodingException;
import java.util.Random;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;




public class StringUtils {
	private static final Logger logger = LoggerFactory.getLogger(StringUtils.class);
	/*
	 * PS: 如有其它需求 可以调用  org.apache.commons.lang.StringUtils
	 * 
	 * */
	public static void main(String[] args) {
//		System.out.println("com.uzg.bcp.utils.tag".split("\\."));
//		System.out.println(StringUtils.subStringBefore("com.uzg.bcp.utils.tag", "\\.", 3));
//		System.out.println(StringUtils.subStringAfter("com.uzg.bcp.utils.tag", "\\.", 4));
		System.out.println(StringUtils.subStringAfter("/wuyo/fms/sss/welcom.html","fms",1));
		String templatePath = "sss/sfs.html";
		System.out.println(templatePath.replace(".html", ".ftl"));
	}

	/**
	*@Author Rambo
	*@Desc：String转Integer
	*@param str
	*@return TODO
	*@Version  StringUtils.java,v 1.1 2013-10-17 下午4:54:03 
	*/
	public static Integer String2Integer(String str){
		Integer i = new Integer("0");
		try {
			i = Integer.valueOf(str);
		} catch (Exception e) {
			logger.error("格式错误："+str);
		}finally{
			return i;
		}	
	}
	/**
	*@Author Rambo
	*@Desc：如果异常赋予默认 defaultInt
	*@param str
	*@param defaultInt
	*@return TODO
	*@Version  StringUtils.java,v 1.1 2014-9-12 下午3:37:32 
	*/
	public static Integer String2Integer(String str,Integer defaultInt){
		Integer i = new Integer("0");
		try {
			i = Integer.valueOf(str);
		} catch (Exception e) {
			i = defaultInt;
			logger.error("格式错误："+str);
		}finally{
			return i;
		}	
	}
	/**
	*@author Kenshinbo@163.com
	*@描述：从头截取第N个重复的字符串
	*@param str
	*@param subStr
	*@param index
	*@return 
	*@version  StringUtils.java,v 1.1 Mar 2, 2011 6:47:57 PM KB
	*/
	public static String subStringBefore(String str,String subStr,int index){
		StringBuilder sb = new StringBuilder();
		String[] strs = str.split(subStr);
		String code = subStr.equals("\\.")?".":subStr;
		if(strs.length>=(index+1)){
			for(int i=0;i<index;i++){
				if(i == 0){
					sb.append(strs[i]);
				}else{
					sb.append(code+strs[i]);
				}				
			}
		}else{
			return "Error !";
		}
		
		return sb.toString(); 
	}
	/**
	*@author Kenshinbo@163.com
	*@描述：从第N个重复的字符串截取
	*@param str
	*@param subStr
	*@param index
	*@return 
	*@version  StringUtils.java,v 1.1 Mar 2, 2011 6:54:34 PM KB
	*/
	public static String subStringAfter(String str,String subStr,int index){
		StringBuilder sb = new StringBuilder();
		String[] strs = str.split(subStr);
		String code = subStr.equals("\\.")?".":subStr;
		if(strs.length>=(index+1)){
			for(int i=index;i<=(strs.length-1);i++){
				if(i == index){
					sb.append(strs[i]);
				}else{
					sb.append(code+strs[i]);
				}
			}
		}else{
			return "Error !";
		}
		
		return sb.toString(); 
	}
	 /**
	   * 生成指定位数的随机数
	   * @param num int 位数
	   * @return int
	   */
	  public static String getRand(int length) {
	    Random random = new Random();
	    String rand = "";

	    for (int i = 0; i < length; i++)
	      rand += String.valueOf(random.nextInt(10));

	    return rand;
	  }

	  /**
	   * 在字符串的右边拼上指定的字符，使得结果字符串为指定的长度
	   * @param strSrc String  被拼接的字符串
	   * @param length int　　　返回结果的长度
	   * @param strPad String  拼接的字符串
	   * @return String
	   */
	  static public String lpad(String strSrc, int length, String strPad) {
	    if (strSrc == null || strSrc.length() >= length)
	      return strSrc;

	    int count = (length-strSrc.length())/strPad.length();

	    String temp = repeat(count, strPad);

	    return temp + strPad.substring(0, length-strSrc.length()-temp.length()) + strSrc;
	  }

	  /**
	   * 在字符串的左边拼上指定的字符，使得结果字符串为指定的长度
	   * @param strSrc String  被拼接的字符串
	   * @param length int　　　返回结果的长度
	   * @param strPad String  拼接的字符串
	   * @return String
	   */
	  static public String rpad(String strSrc, int length, String strPad) {
	    if (strSrc == null || strSrc.length() >= length)
	      return strSrc;

	    int count = (length-strSrc.length())/strPad.length();

	    String temp = repeat(count, strPad);

	    return strSrc + temp + strPad.substring(0, length-strSrc.length()-temp.length());
	  }
	  /**
	   * 生成重复 n 次的指定字符串, 如果 repeat(3, "ab") 得到 "ababab"
	   * @param n int          重复次数
	   * @param strPad String  重复字符串
	   * @return String
	   */
	  static public String repeat(int n, String strPad) {
	    String temp = "";

	    for (int i=0; i<n; i++) {
	      temp = temp.concat(strPad);
	    }

	    return temp;
	  }
	/**
	*@author Kenshinbo
	*@描述：判断传入的String是否为null或是空串
	*@param str
	*@return 
	*@version  CommonUtils.java,v 1.1 Aug 7, 2010 10:02:49 AM BOBO-L-NEAR 
	*/
	public static boolean isStringEmpty(String str){
		  return (str == null || str.trim().equals(""));
	  }
	/**
	*@author Kenshinbo@163.com
	*@描述：重构字符串
	*@param str 源字符串
	*@param rs 如果为空则以该字符串改造
	*@return 
	*@version  CommonUtils.java,v 1.1 Aug 18, 2010 5:31:41 PM KB
	*/
	public static String string2string(String str,String rs){
		  if(null == str ||str.trim().equals("")){
			  return rs;
		  }else{
			  return str.trim();
		  }
	  }
	/**
	*@author Kenshinbo@163.com
	*@描述：返回object string
	*@param o
	*@param rs
	*@return 
	*@version  StringUtils.java,v 1.1 Mar 13, 2012 10:06:18 AM KB
	*/
	public static String object2string(Object o,String rs){
		  if(null == o ){
			  return rs;
		  }else{
			  return o.toString().trim();
		  }
	  }
	/**
	*@author Kenshinbo
	*@描述：判断字符型串是否含有特殊字符
	*@param str
	*@return 
	*@version  CommonUtils.java,v 1.1 Aug 7, 2010 10:03:00 AM BOBO-L-NEAR 
	*/
	public static boolean chkIsContainSpecialStr(String str){
		if(isStringEmpty(str)) return false;
		
		String strSource ="|&;$%@\'\"<>()+,\n\f";
		 for (int i=0;i<strSource.length();i++)
		  {
		  
		    String ch = strSource.substring(i, i+1);
		    if (str.indexOf(ch)!=-1) 
		    {
		    	return true;
		    }
		  }
		return false;
		
	}
	
	  /**
	*@author Kenshinbo
	*@描述：将字符串转成utf8格式
	*@param s
	*@return 
	*@version  CommonUtils.java,v 1.1 Aug 7, 2010 11:37:41 AM BOBO-L-NEAR 
	*/
	public static String toUtf8String(String s) {
		//     System.out.println("utf8="+s);
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < s.length(); i++) {
			char c = s.charAt(i);
			if (c >= 0 && c <= 255) {
				sb.append(c);
			} else {
				byte[] b;
				try {
					b = Character.toString(c).getBytes("utf-8");
				} catch (Exception ex) {
					System.out.println(ex);
					b = new byte[0];
				}
				for (int j = 0; j < b.length; j++) {
					int k = b[j];
					if (k < 0)
						k += 256;
					sb.append("%" + Integer.toHexString(k).toUpperCase());
				}
			}
		}
		return sb.toString();
	}
	public static String toGBK(String str) {
		try {
			str = java.net.URLEncoder.encode(str, "GBK");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return str;
	}
	public static String toUTF8(String str) {
		try {
			str = java.net.URLEncoder.encode(str, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return str;
	}
	public static String toISO(String str) {
		try {
			str = java.net.URLEncoder.encode(str, "ISO-8859-1");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return str;
	}
	 /**
     * 替换字符串中的指定字符，类似String.replaceAll的方法，但去除了正则表达式的应用
     * 
     * @param srcText 源字符串
     * @param fromStr 需要替换的字符串
     * @param toStr 替换为的字符串
     * @return 替换后的字符串
     */
    public static String replace(String srcText, String fromStr, String toStr) {
        if (srcText == null)
            return null;
        StringBuffer rtnVal = new StringBuffer();
        String rightText = srcText;
        for (int i = rightText.indexOf(fromStr); i > -1; i = rightText.indexOf(fromStr)) {
            rtnVal.append(rightText.substring(0, i));
            rtnVal.append(toStr);
            rightText = rightText.substring(i + fromStr.length());
        }
        rtnVal.append(rightText);
        return rtnVal.toString();
    }
	/**
     * 转义like语句中的 <code>'_'</code><code>'%'</code> 将<code>'?'</code>转成sql的<code>'/_'</code>
     * 将<code>'%'</code>转成sql的<code>'/%'</code>
     * <p>
     * 例如搜索<code>?aa*bb?c_d%f</code>将转化成<br/> <code>_aa%bb_c/_d/%f</code>
     * </p>
     * 
     * @param likeStr
     * @return
     * @author <a href="http://jdkcn.com">somebody</a>
     */
    public static String escapeSQLLike(String likeStr) {
        String str = StringUtils.replace(likeStr, "_", "/_");
        str = StringUtils.replace(str, "%", "/%");
        str = StringUtils.replace(str, "?", "_");
        str = StringUtils.replace(str, "*", "%");
        return str;
    }

    /**
     * 连接字符串，常用与HQL语句的拼装，当左边值为空时返回右边值，当右边值为空时返回左边值，左右的值都不为空时返回左边值+连接串+右边值
     * 
     * @param leftStr 左边的值
     * @param linkStr 连接字符串
     * @param rightStr 右边的值
     * @return 连接后的字符串
     */
    public static String linkString(String leftStr, String linkStr, String rightStr) {
        if (isStringEmpty(leftStr))
            return rightStr;
        if (isStringEmpty(rightStr))
            return leftStr;
        return leftStr + linkStr + rightStr;
    }
/**
     * 转换字符串中HTML/XML敏感的字符。
     * 
     * @param src 源字符串
     * @return 转换后的字符串
     */
    public static String XMLEscape(String src) {
        if (src == null)
            return null;
        String rtnVal = src.replaceAll("&", "&amp;");
        rtnVal = rtnVal.replaceAll("\"", "&quot;");
        rtnVal = rtnVal.replaceAll("<", "&lt;");
        rtnVal = rtnVal.replaceAll(">", "&gt;");
        return rtnVal;
    }
}
